package com.zzf.mall.order.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zzf.common.constant.OrderConstant;
import com.zzf.common.dto.SeckillOrderDTO;
import com.zzf.common.exception.NoStockExecption;
import com.zzf.common.utils.R;
import com.zzf.common.vo.MemberVO;
import com.zzf.mall.order.dto.OrderCreateTO;
import com.zzf.mall.order.entity.OrderItemEntity;
import com.zzf.mall.order.fegin.CartFeginService;
import com.zzf.mall.order.fegin.MemberFeginService;
import com.zzf.mall.order.fegin.ProductService;
import com.zzf.mall.order.fegin.WareFeginService;
import com.zzf.mall.order.interceptor.AuthInterceptor;
import com.zzf.mall.order.service.OrderItemService;
import com.zzf.mall.order.utils.OrderMsgProducer;
import com.zzf.mall.order.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzf.common.utils.PageUtils;
import com.zzf.common.utils.Query;

import com.zzf.mall.order.dao.OrderDao;
import com.zzf.mall.order.entity.OrderEntity;
import com.zzf.mall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private MemberFeginService menberFeginService;

    @Autowired
    private CartFeginService cartFeginService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductService productService;

    @Autowired
    OrderService orderService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    WareFeginService wareFeginService;

    @Autowired
    OrderMsgProducer orderMsgProducer;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取订单确认页中的相关信息
     * @return
     */
    @Override
    public OrderConfirmVO confirmOrder() {

        OrderConfirmVO vo = new OrderConfirmVO();
        MemberVO memberVO = (MemberVO) AuthInterceptor.threadLocal.get();
        // 获取到 RequestContextHolder 的相关信息
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            // 同步主线程中的 RequestContextHolder
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //查询当前登录会员的收货地址
            Long id = memberVO.getId();
            List<MemberAddressVO> addresses = menberFeginService.getAddress(id);
            vo.setAddress(addresses);
        }, threadPoolExecutor);
        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            // 同步主线程中的 RequestContextHolder
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //查询购物车选中的商品信息
            List<OrderItemVO> userCartItems = cartFeginService.getUserCartItems();
            vo.setItems(userCartItems);
        }, threadPoolExecutor);
        try {
            CompletableFuture.allOf(future1,future2).get();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //生成翻翻重token
        String token = UUID.randomUUID().toString().replace("-", "");
        //把token放进redis当中
        redisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN_PREFIX+":"+memberVO.getId(),token);
        //将token绑定响应的数据库对象中
        vo.setOrderToken(token);

        return vo;
    }

    private Lock lock = new ReentrantLock();

    /**
     * @param vo
     * @return
     * @throws NoStockExecption
     */
    //@GlobalTransactional
    @Transactional()
    @Override
    public OrderResponseVO submitOrder(OrderSubmitVO vo) throws NoStockExecption {
        // 需要返回响应的对象
        OrderResponseVO responseVO = new OrderResponseVO();

        // 获取当前登录的用户信息
        MemberVO memberVO = (MemberVO) AuthInterceptor.threadLocal.get();
        // 1.验证是否重复提交  保证Redis中的token 的查询和删除是一个原子性操作
        String key = OrderConstant.ORDER_TOKEN_PREFIX+":"+memberVO.getId();
       String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class)
                , Arrays.asList(key)
                , vo.getOrderToken());
         if(result == 0){
            // 验证失败 重复提交
            responseVO.setCode(1);
            return responseVO;
        }

        //创建订单
        OrderCreateTO orderCreateTO = createOrder(vo);
        responseVO.setOrderEntity(orderCreateTO.getOrderEntity());

        //保存订单信息
        saveOrder(orderCreateTO);
        //锁定库存信息
        lockWareSkuStock(responseVO, orderCreateTO);

        //int i = 10/0;

        // 订单成功后需要给 消息中间件发送延迟30分钟的关单消息
        orderMsgProducer.sendOrderMessage(orderCreateTO.getOrderEntity().getOrderSn());

        return responseVO;
    }

    @Override
    public PayVO getOrderPay(String orderSn) {

        //根据订单号查询出对应的订单信息
        OrderEntity orderEntity = this.getBaseMapper().getOrderByOrderSn(orderSn);
        //通过订单信息封装vo对象
        PayVO payVO = new PayVO();
        payVO.setOut_trader_no(orderSn);
        payVO.setTotal_amount(orderEntity.getTotalAmount().setScale(2, RoundingMode.UP).toString());
        //订单名称和描述
        payVO.setSubject(orderEntity.getOrderSn());
        payVO.setBody(orderEntity.getOrderSn());

        return payVO;
    }

    /**
     * 更新订单状态
     * @param orderSn
     * @param status
     */
    @Override
    public void updateOrderStatus(String orderSn,Integer status) {
        this.getBaseMapper().updateOrderStatus(orderSn,status);
    }

    @Override
    public void handleOrderComplete(String orderSn) {
        //更新订单状态
        this.updateOrderStatus(orderSn, OrderConstant.OrderStateEnum.TO_SEND_GOODS.getCode());

    }

    /**
     * 快速完成订单的处理  秒杀活动
     * @param orderDTO
     */
    @Transactional
    @Override
    public void quickCreateOrder(SeckillOrderDTO orderDTO) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderDTO.getOrderSN());
        orderEntity.setStatus(OrderConstant.OrderStateEnum.FOR_THE_PAYMENT.getCode());
        orderEntity.setMemberId(orderDTO.getMemberId());
        orderEntity.setTotalAmount(orderDTO.getSeckillPrice().multiply(new BigDecimal(orderDTO.getNum())));
        this.save(orderEntity);
        OrderItemEntity itemEntity = new OrderItemEntity();
        // TODO 根据SKUID查询对应的SKU信息和SPU信息
        itemEntity.setOrderSn(orderDTO.getOrderSN());
        itemEntity.setSkuPrice(orderDTO.getSeckillPrice());
        itemEntity.setSkuId(orderDTO.getSkuId());
        itemEntity.setRealAmount(orderDTO.getSeckillPrice().multiply(new BigDecimal(orderDTO.getNum())));
        itemEntity.setSkuQuantity(orderDTO.getNum());

        orderItemService.save(itemEntity);
    }

    /**
     * 锁定库存信息
     * @param responseVO
     * @param orderCreateTO
     * @throws NoStockExecption
     */
    private void lockWareSkuStock(OrderResponseVO responseVO, OrderCreateTO orderCreateTO) throws NoStockExecption{
        WareSkuLockVO wareSkuLockVO = new WareSkuLockVO();
        wareSkuLockVO.setOrderSN(orderCreateTO.getOrderEntity().getOrderSn());
        List<OrderItemVO> orderItemVOS = orderCreateTO.getOrderItemEntitys().stream().map(item -> {
            OrderItemVO itemVO = new OrderItemVO();
            itemVO.setSkuId(item.getSkuId());
            itemVO.setTitle(item.getSkuName());
            itemVO.setCount(item.getSkuQuantity());
            return itemVO;
        }).collect(Collectors.toList());
        wareSkuLockVO.setItems(orderItemVOS);
        // 远程锁库存的操作
        R r = wareFeginService.orderLockStock(wareSkuLockVO);
        if(r.getCode() == 0){
            // 表示锁定库存成功
            responseVO.setCode(0); // 表示 创建订单成功
        }else{
            // 表示锁定库存失败
            responseVO.setCode(2); // 表示库存不足，锁定失败
            throw new NoStockExecption(10000l);
        }
    }

    /**
     * 生成订单数据
     * @param orderCreateTO
     */
    private void saveOrder(OrderCreateTO orderCreateTO) {

        // 订单数据
        OrderEntity orderEntity = orderCreateTO.getOrderEntity();
        orderService.save(orderEntity);
        // 订单项数据
        List<OrderItemEntity> orderItemEntitys = orderCreateTO.getOrderItemEntitys();
        orderItemService.saveBatch(orderItemEntitys);

    }

    /**
     * 创建订单服务
     * @param vo
     * @return
     */
    private OrderCreateTO createOrder(OrderSubmitVO vo) {

        OrderCreateTO createTO = new OrderCreateTO();
        //创建订单
        OrderEntity orderEntity = buildOrder(vo);
        createTO.setOrderEntity(orderEntity);
        //创建订单项
        List<OrderItemEntity> orderItemEntitys = buildOrderItems(orderEntity.getOrderSn());
        //根据订单项计算出订单的总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItemEntity orderItemEntity : orderItemEntitys) {
            BigDecimal total = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity()));
            totalAmount = totalAmount.add(total);
        }
        orderEntity.setTotalAmount(totalAmount);
        createTO.setOrderItemEntitys(orderItemEntitys);

        return createTO;
    }

    /**
     * 根据已选中的购物车信息创建购物项信息
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSN) {
        List<OrderItemEntity> orderItemEntities = new ArrayList<>();
        //获取已选中的购物车信息
        List<OrderItemVO> userCartItems = cartFeginService.getUserCartItems();
        if (userCartItems != null && userCartItems.size() > 0){
            //统一根据skuId查询出对应的spu信息
            List<Long> spuIds = new ArrayList<>();
            for (OrderItemVO orderItemVO : userCartItems) {
                if (!spuIds.contains(orderItemVO.getSpuId())){
                    spuIds.add(orderItemVO.getSpuId());
                }
            }
            Long[] spuIdsArray = new Long[spuIds.size()];
            spuIdsArray = spuIds.toArray(spuIdsArray);
            //远程调用商品服务获取对应的spu信息
            List<OrderItemSpuInfoVO> spuInfos = productService.getOrderItemSpuInfoBySpuId(spuIdsArray);
            Map<Long, OrderItemSpuInfoVO> map = spuInfos.stream().collect(Collectors.toMap(OrderItemSpuInfoVO::getId, item -> item));
            for (OrderItemVO userCartItem : userCartItems) {
                // 获取到商品信息对应的 SPU信息
                OrderItemSpuInfoVO spuInfo  = map.get(userCartItem.getSpuId());
                OrderItemEntity orderItemEntity = buildOrderItem(userCartItem,spuInfo);
                // 绑定对应的订单编号
                orderItemEntity.setOrderSn(orderSN);
                orderItemEntities.add(orderItemEntity);
            }
        }


        return orderItemEntities;
    }

    /**
     * 根据购物车选中的商品信息 创建相应的订单项
     * @param userCartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVO userCartItem,OrderItemSpuInfoVO spuInfo) {
        OrderItemEntity entity = new OrderItemEntity();
        // SKU信息
        entity.setSkuId(userCartItem.getSkuId());
        entity.setSkuName(userCartItem.getTitle());
        entity.setSkuPic(userCartItem.getImage());
        entity.setSkuQuantity(userCartItem.getCount());
        List<String> skuAttr = userCartItem.getSkuAttr();
        String skuAttrStr = StringUtils.collectionToDelimitedString(skuAttr, ";");
        entity.setSkuAttrsVals(skuAttrStr);

        // SPU信息
        entity.setSpuId(spuInfo.getId());
        entity.setSpuBrand(spuInfo.getBrandName());
        entity.setCategoryId(spuInfo.getCatalogId());
        entity.setSpuPic(spuInfo.getImg()); // SPU信息
        entity.setSpuId(spuInfo.getId());
        entity.setSpuBrand(spuInfo.getBrandName());
        entity.setCategoryId(spuInfo.getCatalogId());
        entity.setSpuPic(spuInfo.getImg());

        // 积分信息
        entity.setGiftGrowth(userCartItem.getPrice().intValue());
        entity.setGiftIntegration(userCartItem.getPrice().intValue());
        entity.setSkuPrice(userCartItem.getPrice());

        return entity;
    }

    private OrderEntity buildOrder(OrderSubmitVO vo) {
        // 创建OrderEntity
        OrderEntity orderEntity = new OrderEntity();
        // 创建订单编号
        String orderSn = IdWorker.getTimeId();
        orderEntity.setOrderSn(orderSn);
        MemberVO memberVO = (MemberVO) AuthInterceptor.threadLocal.get();
        // 设置会员相关的信息
        orderEntity.setMemberId(memberVO.getId());
        orderEntity.setMemberUsername(memberVO.getUsername());
        // 根据收获地址ID获取收获地址的详细信息
        MemberAddressVO memberAddressVo = menberFeginService.getAddressById(vo.getAddrId());
        orderEntity.setReceiverCity(memberAddressVo.getCity());
        orderEntity.setReceiverDetailAddress(memberAddressVo.getDetailAddress());
        orderEntity.setReceiverName(memberAddressVo.getName());
        orderEntity.setReceiverPhone(memberAddressVo.getPhone());
        orderEntity.setReceiverPostCode(memberAddressVo.getPostCode());
        orderEntity.setReceiverRegion(memberAddressVo.getRegion());
        orderEntity.setReceiverProvince(memberAddressVo.getProvince());
        // 设置订单的状态
        orderEntity.setStatus(OrderConstant.OrderStateEnum.FOR_THE_PAYMENT.getCode());
        return orderEntity;
    }

}